package com.util;

import com.bean.Orders;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SelectOrder {
    private String id = "sa";
    private String pwd = "123456";
    private String url = "jdbc:sqlserver://127.0.0.1:1433;databaseName=FarmProductSalesSystem";
    private List<Orders> orderList;
    public List<Orders> getOrderData(){
        orderList = new ArrayList<>();
        try {
            //加载驱动
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //获取连接
        Connection conn = null;
        Statement stat = null;
        ResultSet rs = null;
        try {
            conn = DriverManager.getConnection(url,id,pwd);
            String sql = "select * from Orders";
            stat = conn.createStatement(); //用于执行sql语句
            rs = stat.executeQuery(sql); //返回查询后的结果
            while(rs.next()){
                String OrderID = rs.getString("OrderID");
                int UserID = rs.getInt("UserID");
                int ProductID = rs.getInt("ProductID");
                int FarmerID = rs.getInt("FarmerID");
                int Quantity = rs.getInt("Quantity");
                String PurchaseDate = rs.getString("PurchaseDate");
                Double TotalPrice = rs.getDouble("TotalPrice");
                int Status = rs.getInt("Status");
                Orders order = new Orders(OrderID,UserID,FarmerID,ProductID,Quantity,PurchaseDate,TotalPrice,Status);
                orderList.add(order);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("连接数据库失败！");
        }finally{
            //关闭coon
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

            //关闭stat
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

            //关闭rs
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return orderList;
    }

    public String getOrderID(){
        List<Orders> list = getOrderData();
        String ID = "";
        for(Orders order:list)
        {
            ID = order.getOrderID();
        }
        return ID;
    }

    //获取的是最后一个订单编号的后四位+1的数
    public String getOrderIDLast(){
        List<Orders> list = getOrderData();
        String ID = "";
        for(Orders order:list)
        {
            //截取字符串后四位
            ID = order.getOrderID().substring(order.getOrderID().length()-4);
        }
        return Integer.parseInt(ID)+1+"";
    }
}
